package cn.jolyoulu.adminweb.utils;

import cn.jolyoulu.common.core.utils.encryption.DESUtils;
import cn.jolyoulu.common.redis.utils.RedisUtils;
import cn.jolyoulu.common.web.enums.GlobalExpType;
import cn.jolyoulu.common.web.excption.GlobalException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import cn.jolyoulu.cmnservice.constant.ServiceRedisConstant;

import java.util.concurrent.TimeUnit;

/**
 * @Author: JolyouLu
 * @Date: 2023/3/18 20:39
 * @Description
 */
@Component
public class AuthUtils {

    @Autowired
    private RedisUtils redisUtils;

    private static final String KEY = "12345678";

    public String genToken(String userId) {
        String token = ServiceRedisConstant.getToken(userId);
        //添加随机数时token不断刷新
        String source = token + ":" + System.currentTimeMillis();
        String encode = DESUtils.encrypt(source, KEY);
        //保存Token
        redisUtils.set(token, encode, 30, TimeUnit.MINUTES);
        return encode;
    }

    public String getUserId(String token) {
        try {
            String decode = DESUtils.decrypt(token, KEY);
            String userId = "";
            if (StringUtils.isNotBlank(decode)) {
                String[] split = decode.split(":");
                userId = split[split.length - 2];
            }
            return userId;
        }catch (Exception e){
            throw new GlobalException(GlobalExpType.TOKEN_NO_AVAIL);
        }

    }

}
